=begin

Example:

    o = Opencall.new
    o.cust_id = 'mxrguspxrt'
    o.owner = 'mxrguspxrt'
    o.loggedby = 'mxrguspxrt'
    o.prob_text = 'prob_text'
    o.callclass = 'Incident'
    o.ria_environment = 'Test'
    o.save


TODO:
    * Use some AOP framework and aspects instead of before_* and inject (to make it more logically followable)

BUGS (imho):
    * Supportworks: When saving prob_text has to be updatedb.updatetxt (first time this will be prob_text, later update)

=end

# riaproxy_post
include ApplicationHelper


class Opencall < ActiveRecord::Base
    self.table_name  = "opencall"
    self.primary_key = "callref"
    
    belongs_to  :customer,      :class_name => "User",  :foreign_key => "cust_id"
    belongs_to  :reporter,      :class_name => "User",  :foreign_key => "loggedby"
    belongs_to  :responsible,   :class_name => "User",  :foreign_key => "owner"
    has_many    :updates,       :class_name => "OpencallUpdate", :foreign_key => "callref"

    validates_presence_of :suppgroup, :cust_id, :loggedby, :prob_text, :callclass, :priority


    # If exists (id exists) update, else create
    def before_save
        if not self.id.nil?
            self.before_update
        else
            self.before_create
        end
    end
    
    # Create call
    def before_create
        # Set attributes + bugfix
        attrs       = self.attributes['prob_text'].nil? ? self.attributes : self.attributes.merge({'updatedb.updatetxt' => self.attributes['prob_text']})
        # Create call
        response    = riaproxy_post('LOG CALL', attrs)
        # Get call id and do magic
        save_ok     = response['return']['command'] && response['return']['commit']
        if save_ok
            # Set callref gotten back from SupportWorks, also refresh object silently from DB
            self.id     = response['output']['commit'].match(/(?<=callref\=F)[\d]*/)[0].to_i
            self.reload
        else
            print "\n\nsave nok\n\n"
        end 
        save_ok
    end

    # Update call
    def before_update
        # Set attributes + bugfix
        attrs       = self.attributes['prob_text'].nil? ? self.attributes : self.attributes.merge({'updatedb.updatetxt' => self.attributes['prob_text']})
        # Create call
        response    = riaproxy_post('UPDATE CALL', attrs)        
        save_ok     = response['return']['command'] && response['return']['commit']
    end

    # Replace default save (no call to DB is done)
    def save; self.before_save; end

    # Replace default save! (no call to DB is done)
    def save!; self.before_save; end

    # Replace default update (no call to DB is done)
    def update; self.before_save; end




end





